"""
用户模型
定义用户、权限相关的数据库模型
"""
from datetime import datetime
import enum
from werkzeug.security import generate_password_hash, check_password_hash
from app.extensions import db

class UserRole(enum.Enum):
    """用户角色枚举"""
    ADMIN = 'admin'  # 管理员
    MANAGER = 'manager'  # 经理
    OPERATOR = 'operator'  # 操作员
    USER = 'user'  # 普通用户

class User(db.Model):
    """用户模型"""
    __tablename__ = 'user'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False, index=True)
    email = db.Column(db.String(100), unique=True, nullable=False, index=True)
    password_hash = db.Column(db.String(128), nullable=False)
    full_name = db.Column(db.String(100))
    role = db.Column(db.String(20), nullable=False, default=UserRole.USER.value)
    is_active = db.Column(db.Boolean, default=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    orders = db.relationship('Order', backref='user', lazy='dynamic')
    inventory_records = db.relationship('InventoryRecord', backref='operator', lazy='dynamic')
    
    def __repr__(self):
        return f'<User {self.username}>'
    
    def set_password(self, password):
        """设置密码"""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
    
    @property
    def is_admin(self):
        """判断是否为管理员"""
        return self.role == UserRole.ADMIN.value
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'full_name': self.full_name,
            'role': self.role,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None
        } 